<?php
class GridSelectControl extends BaseControl
{
	protected $viewName;
    protected $drop;
    protected $displayField;
    protected $selectedKey;
    protected $selectedDisplayvalue;
    protected $jsFile = 'GridSelectControl';
    protected $resourceId = 'SystemResource';

    public function GridSelectControl($view_name, $name, $displayfield, $selected_key = null, $selected_displayvalue = null)
	{
		parent::__construct($name);
        $this->SetViewName($view_name);
        $this->displayField = $displayfield;
        $this->selectedKey  = $selected_key;
        $this->selectedDisplayvalue = $selected_displayvalue;
        $this->drop = new GridListControl($this->viewName, 'drop_'.$this->viewName, $displayfield);
	}

    public function GetConfig()
    {
        return GridConfig::GetInstance();
    }

    public function Render()
	{
        $drop = $this->drop->Render();
        $data = $this->drop->GetData();
        if(is_null($this->selectedKey))
            $value = empty($data) ? null : $this->GetFirstItemValue($data, 'id');
        else
            $value = $this->selectedKey;

        if(is_null($this->selectedDisplayvalue))
            $display = empty($data) ? null : $this->GetFirstItemValue($data, $this->displayField);
        else
            $display = $this->selectedDisplayvalue;

        if(!empty($this->selectedKey) && empty($this->selectedDisplayvalue))
            $display = $this->GetDisplayvalueByKey($this->selectedKey);

		$this->Replace('name', $this->name);
        $this->Replace('value', $value);
        $this->Replace('display', $display);
		$this->Replace('id', 'gridselect_'.$this->viewName);
		$this->Replace('dropname', $this->drop->name);
		return $this->Replace('drop', $drop);
	}

    public function GetFirstItemValue($items, $field)
    {
        $item = array_shift($items);
        return $item[$field];
    }

    public function FilterBy($field, $value)
    {
        $this->drop->FilterBy($field, $value);
    }

    public function SetViewName($view_name)
    {
        $this->viewName = $view_name;
        $this->model = VmViewModel::GetInstance()->GetModelById($view_name);
    }

    public function GetDisplayvalueByKey($key)
    {
        if($this->model)
        {
            return $this->model->FindScalarById($key, $this->displayField);
        }
    }
}
?>
